package com.shanzmoo.db.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.db.sys.entity.AddressEntity;
import com.shanzmoo.db.sys.entity.vo.AddressTreeVo;
import com.shanzmoo.db.sys.mapper.AddressMapper;
import com.shanzmoo.db.sys.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gzhao
 * @since 2020-12-08
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressEntity> implements IAddressService {

    @Override
    public List<AddressTreeVo> getAddressTree() {

        List<AddressEntity> list = baseMapper.selectList(
                new QueryWrapper<AddressEntity>()
                        .eq("deleted", false)
        );
        // 省
        List<AddressTreeVo> provinceList = list.stream()
                .filter(e->e.getParentCode() == 0)
                .map(AddressTreeVo::create)
                .collect(Collectors.toList());
        // 市
        provinceList.forEach(province->{
            List<AddressTreeVo> cityList = list.stream()
                    .filter(e->Objects.equals(e.getParentCode(), province.getAddressCode()))
                    .map(AddressTreeVo::create)
                    .collect(Collectors.toList());
            province.setChildren(cityList);

            // 区
            cityList.forEach(city->{
                List<AddressTreeVo> countyList = list.stream()
                        .filter(e->Objects.equals(e.getParentCode(), city.getAddressCode()))
                        .map(AddressTreeVo::create)
                        .collect(Collectors.toList());
                city.setChildren(countyList);
            });
        });
        return provinceList;
    }
}
